function plot_node_elem_edge_2d(node, elem, basis_type)

switch basis_type
    case {"P1", "Q1"}
        original_elem = elem;

    case {"P1b", "P2"}
        original_elem = elem(:,1:3);

    case {"Q1b", "Q2"}
        original_elem = elem(:,1:4);

    otherwise
        error('Invalid basis type');
end

showmesh(node, original_elem);
findnode(node);
% findelem(node, original_elem);
% findedge(node, original_elem);

end


function showmesh(node, elem)

h = patch('Faces', elem, 'Vertices', node);

set(h, 'facecolor', [0.5 0.9 0.45], 'edgecolor', 'k');
axis equal;
axis tight;

end


function findnode(node, range)

hold on

if nargin == 1
    range = (1:size(node,1))';
end

plot(node(range,1), node(range,2), 'k.', 'MarkerSize', 15);
text(node(range,1)+0.015, node(range,2)+0.015, int2str(range), 'FontSize', 12, 'FontWeight', 'bold');

hold off

end


function findelem(node, elem, varargin)

hold on

Ne = size(elem, 1);

if ~iscell(elem)
    elem = mat2cell(elem, ones(Ne,1), length(elem(1,:)));
end

range = 1:Ne;

if nargin == 3
    range = unique(varargin{1});
end
range = range(:);

center = zeros(length(range),2);
s = 1;
for i = range(:)'
    index = elem{i};
    V = node(index,:);
    center(s,:) = polygon_centroid(V);
    s = s+1;
end
% plot(center(:,1), center(:,2), 'o', 'LineWidth', 1, 'MarkerEdgeColor', 'k', 'MarkerFaceColor', 'y', 'MarkerSize', 18);
text(center(:,1), center(:,2), int2str(range), 'FontSize', 12, 'FontWeight', 'bold', 'Color','r');

hold off

end


function findedge(node, elem, varargin)

hold on

Ne = size(elem, 1);

if ~iscell(elem)
    elem = mat2cell(elem, ones(Ne,1), length(elem(1,:)));
end

shiftfun = @(verts) [verts(2:end),verts(1)];
T1 = cellfun(shiftfun, elem, 'UniformOutput', false);
v0 = horzcat(elem{:})';
v1 = horzcat(T1{:})';
totalEdge = sort([v0,v1],2);

sparseIndex = sparse(totalEdge(:,2),totalEdge(:,1),1);
diag_zero = spdiags(diag(sparseIndex),0,size(sparseIndex,1),size(sparseIndex,2));
[i,j,s] = find(sparseIndex-diag_zero);
edge = [j,i];
% edge = unique(totalEdge,'rows');

range = (1:size(edge,1))';
midEdge = (node(edge(range,1),:) + node(edge(range,2),:))/2;

if nargin == 2
    % plot(midEdge(:,1), midEdge(:,2), 's', 'LineWidth', 1, 'MarkerEdgeColor', 'k', 'MarkerFaceColor', [0.6 0.5 0.8], 'MarkerSize', 20);
    text(midEdge(:,1), midEdge(:,2), int2str(range(:)), 'FontSize', 12, 'FontWeight', 'bold', 'Color', 'y');
end
if nargin == 3
    % plot(midEdge(s==1,1), midEdge(s==1,2), 's', 'LineWidth', 1, 'MarkerEdgeColor', 'k', 'MarkerFaceColor', [0.6 0.5 0.8], 'MarkerSize', 20);
    text(midEdge(s==1,1), midEdge(s==1,2), int2str(range(s==1)), 'FontSize', 12, 'FontWeight', 'bold', 'Color', 'y');
end

hold off

end